<?php

namespace app\store\model\card;

use app\common\model\card\Card as CardModel;


/**
 * 储值卡-商品模型
 * Class Goods
 * @package app\store\model\sharp
 */
class Card extends CardModel
{
    /**
     * 获取列表数据
     * @param string $search
     * @return mixed|\think\Paginator
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList($search = '')
    {
        // 检索查询条件
        if (!empty($search)) {
            $this->where('card_title', 'like', "%{$search}%");
        }
        // 获取活动列表
        $list = $this->with(['image'])
                ->where(['is_delete'=>0])
                ->paginate(15, false, [
                'query' => \request()->request()
            ]);

        return $list;
    }


    /**
     * 添加储值卡
     * @param $goods
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function add($data)
    {
        // 表单验证
        if (!$this->validateCard($data)) return false;
        // 添加商品
        $this->allowField(true)->save(array_merge($data, [
            'wxapp_id' => self::$wxapp_id,
        ]));

        return true;
    }

    /**
     * 验证商品图片
     * @param $goodsId
     * @return bool
     */
    public function validateCard($data)
    {
        if(!isset($data['image_id']) || empty($data['image_id'])){
            $this->error = '请上传图片';
            return false;
        }
        return true;
    }


    /**
     * 商品ID是否存在
     * @param $goodsId
     * @return bool
     */
    public static function isExistCard()
    {
        return  !!(new static)->where('wxapp_id', '=', self::$wxapp_id)->find();
    }


    /**
     * 编辑商品
     * @param $data
     * @return bool|mixed
     */
    public function edit($data)
    {
        // 表单验证
        if (!$this->validateCard($data)) return false;
        $data['wxapp_id']  = self::$wxapp_id;
        // 保存商品
        $this->allowField(true)->save($data);
        return true;

    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {

        return $this->allowField(true)->save(['is_delete' => 1]);
    }

}